package com.cloud.goal.web;

import java.util.List;

import com.cloud.goal.model.Goal;
import com.cloud.goal.service.GoalService;
import com.cloud.platform.BaseHandler;
import com.cloud.platform.json.JSONArray;
import com.cloud.platform.json.JSONObject;
import com.cloud.platform.util.DateUtil;

public class GoalBean extends BaseHandler {

	private GoalService goalService;
	
	private Goal goal;
	private List<Goal> goalList;
	
	/**
	 * get goals for dwr
	 * 
	 * @return
	 */
	public String dynGetGoals() {
		JSONArray goals = new JSONArray();
		JSONObject goal = null;
		
		try {
			// get goal list
			getGoalList();
			
			// combine json datas
			for(Goal g : goalList) {
				goal = new JSONObject();
				
				goal.put("i", g.getId());
				goal.put("v", g.getName());
				
				goals.put(goal);
			}
			
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return goals.toString();
	}
	
	/**
	 * remove goal
	 */
	public void removeGoal() {
		goalService.removeGoal(getParameter("goalId"));
	}
	
	/**
	 * search user goal list
	 * 
	 * @return
	 */
	public List<Goal> getGoalList() {
		if(goalList == null) {
			goalList = goalService.searchGoals(getLoginUserId());
		}
		return goalList;
	}
	
	/**
	 * save goal
	 */
	public void saveGoal() {
		try {
			String startDate = getParameter("startDate");
			String endDate = getParameter("endDate");
			
			goal.setStartDate(DateUtil.parseDate(startDate));
			goal.setEndDate(DateUtil.parseDate(endDate));
			
			goalService.saveGoal(goal, getLoginUserId());
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * get goal by goal id
	 * 
	 * @return
	 */
	public Goal getGoal() {
		if(goal == null) {
			goal = goalService.getGoal(getParameter("goalId"));
		}
		return goal;
	}

	/**
	 * =======================  getters and setters  =======================
	 */
	public void setGoal(Goal goal) {
		this.goal = goal;
	}
	
	public GoalService getGoalService() {
		return goalService;
	}

	public void setGoalService(GoalService goalService) {
		this.goalService = goalService;
	}
	
	public void setGoalList(List<Goal> goalList) {
		this.goalList = goalList;
	}
}
